package cn.jervain.nut.auth.core.storage;

import cn.jervain.nut.auth.core.exception.AuthException;
import cn.jervain.nut.auth.core.token.Token;
import cn.jervain.nut.auth.core.util.Assert;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Data;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class RedisTokenStorage<T> implements TokenStorage<T> {

    private Map<String, Entry> storage = new HashMap<>();

    @Autowired
    private ObjectMapper objectMapper;


    @Override
    public String put(Token token) {
        String sign = RandomStringUtils.randomAlphanumeric(8);
        try {
            String jsonString = objectMapper.writeValueAsString(token);
            Entry entry = new Entry();
            entry.clz = token.getClass();
            entry.content = jsonString;
            storage.put(sign, entry);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return sign;
    }

    @SuppressWarnings("unchecked")
    @Override
    public Token<T> get(String sign) throws AuthException {
        Entry entry = storage.get(sign);
        Assert.notNull(entry);
        Token<T> token = null;
        try {
            token = (Token<T>) objectMapper.readValue(entry.content, entry.clz);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return token;
    }

    @Data
    private static class Entry {
        private Class clz;
        private String content;
    }

}
